package context

//注册中心
//注册app task module map

var (
	apps             = make(map[string]bool)
	appQueues        = make(map[string][]string)
	appTask          = make(map[string]map[int]bool)
	taskMap          = make(map[int]*TaskHandler)
	taskModuleMap    = make(map[int][]int)
	moduleFuncMap    = make(map[int]ModuleFunc)
	moduleFuncParams = make(map[int][]string)
)

//注册app
func RegisterApp(appName string) {
	if _, ok := apps[appName]; !ok {
		apps[appName] = true
	}
}

func GetAllApp() map[string]bool {
	return apps
}

func AppExist(appName string) bool {
	_, ok := apps[appName]
	return ok
}

//注册mq队列app-queue
func RegisterAppQueue(appName, queueName string) {
	if _, ok := appQueues[appName]; !ok {
		appQueues[appName] = make([]string, 0)
	}
	appQueues[appName] = append(appQueues[appName], queueName)
	RegisterApp(appName)
}

func GetAppQueues(appName string) []string {
	if queues, ok := appQueues[appName]; ok {
		return queues
	}
	return nil
}

//注册app-task
func RegisterAppTask(appName string, taskId, threadNum int) {
	if _, ok := appTask[appName]; !ok {
		appTask[appName] = make(map[int]bool)
	}
	appTask[appName][taskId] = true
	RegisterApp(appName)
	RegisterTask(taskId, threadNum)
}

//获取 app 下的 task
func GetAppTask(queueName string, taskId int) *TaskHandler {
	if tasks, ok := appTask[queueName]; ok {
		if _, ok := tasks[taskId]; ok {
			return GetTask(taskId)
		}
	}
	return nil
}

type TaskFunc func(t interface{}, data interface{})

type TaskHandler struct {
	TaskFunc  []TaskFunc
	ThreadNum int
}

//注册task
func RegisterTask(taskId int, threadNum int) {
	taskMap[taskId] = &TaskHandler{ThreadNum: threadNum, TaskFunc: make([]TaskFunc, 0)}
}

func GetTask(taskId int) *TaskHandler {
	if task, ok := taskMap[taskId]; ok {
		return task
	}
	return nil
}

//注册task-module
func RegisterTaskModule(taskId int, moduleId int) {
	if _, ok := taskModuleMap[taskId]; !ok {
		taskModuleMap[taskId] = make([]int, 0)
	}
	taskModuleMap[taskId] = append(taskModuleMap[taskId], moduleId)
}

//注册module
type ModuleFunc func(ctx *Parser)

func RegisterModule(moduleId int, moduleFunc ModuleFunc, p ...string) {
	moduleFuncMap[moduleId] = moduleFunc
	if len(p) > 0 {
		moduleFuncParams[moduleId] = p[:]
	}
}

func GetModuleFuncParams(moduleId int) []string {
	if params, ok := moduleFuncParams[moduleId]; ok {
		return params
	}
	return nil
}

func GetTaskModuleMap(taskId int) []int {
	if m, ok := taskModuleMap[taskId]; ok {
		return m
	}
	return nil
}

func GetModuleFuncMap(moduleId int) ModuleFunc {
	if f, ok := moduleFuncMap[moduleId]; ok {
		return f
	}
	return nil
}
